import { defineStore } from "pinia";
import { message } from "ant-design-vue";
import { login } from "@/api/index.js";

export const useStore = defineStore("user", {
  state: () => ({
    userinfo: {},
    token: undefined,
    refresh: undefined,
    isLogin: false,
  }),
  actions: {
    async LoginUser(userinfo) {
      try {
        const res = await login(userinfo);
        if (res) {
          const { userinfo, token, refresh } = res;
          this.userinfo = userinfo;
          this.token = token;
          this.refresh = refresh;
          this.isLogin = true;
          message.success("登录成功");
        } else {
          message.error("登录失败");
        }
      } catch (error) {
        message.error(`Login error: ${error.message || error}`);
      }
    },
  },
  getters: {
    avatar: (state) =>
      import.meta.env.VITE_APP_PROXY_TARGET + state.userinfo.avatar,
    userId: (state) => state.userinfo.id,
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "blog_web_user",
        storage: localStorage,
      },
    ],
  },
});
